function editDescr(obj){
    if(window.location.hostname === '192.168.1.38') {
        var descrText = $(obj).html();
        var width = $(obj).width();
        var height = $(obj).height() + 20;
        var fId = $(obj).attr('id');
        var buttonWidth = width + 132;
        $(obj).remove();
        $(".descrText").append('<textarea id="editPlace" style="width: ' + width + 'px; height: ' + height + 'px">' + descrText + '</textarea>');
        $(".descrText").append('<div class="hidden" id="filmId">' + fId + '</div>')
        $(".descrText").append('<div class="right" style="width: ' + buttonWidth + 'px;"><button id="' + fId + '" onclick="writeDescr(); return false;">Сохранить</button><button onclick="resetDescr(); return false;">Перезагрузить</button></div>');
        $("#editPlace").focus();
    }
}

function writeDescr() {
    var name = $("#showName").text();
    var descr = $("#editPlace").val();
    $.getJSON('bin/writeDescr.php', {'name':name, 'descr':descr, 'id':$("#filmId").text()}, function(wData){
        if(wData != 'success') {
            alert(wData);
        }else {
            showDescr(name);
        }
    })
}

function alfListing(){
    var lPattern = '';
    var alfList = [];
    $.getJSON('bin/list.php', function(lData){
        for(var i = 0; i < lData.length; i++) {
            if(lPattern != lData[i][0]) {
                lPattern = lData[i][0];
                $("#alf").append('<a href="javascript:void(0)" onclick="fListing($(this).text())">'+ lData[i][0]+'</a>');
            }
        }
        $("#alf").append('<div style="padding-top: 25px;" class="rating">Всего фильмов: ' + lData.length + '</div>');
    });
}
function fListing(pattern){
    $("#filesPlace").html('');
    $("#descrPlace").removeClass('cBlock');
    $("#descrPlace").html('');
    var listingData = '';
    $.getJSON('bin/list.php', function(pData){
        for(var i = 0; i < pData.length; i++) {
                
            if((pData[i][0] == pattern) || (pData[i][0] == pattern.toLowerCase()) || (pData[i][0] == pattern.toUpperCase()) ) {
                listingData = listingData + '<div class="cItem"><a href="javascript:void(0)" onclick="showDescr($(this).text())">' + pData[i] + '</a></div>'
            } 
        }
        $("#listing").html(listingData);
    })
}

function newFilms(num) {
    $("#filesPlace").html('');
    $("#descrPlace").removeClass('cBlock');
    $("#descrPlace").html('');
    var listingData = '';
    $.getJSON('bin/mtime.php', {'num': num}, function(mData){
        for(var i = mData.name.length-1; i >= 0 ; i--) {
            listingData = listingData + 
            '<div class="cItem">'+
            '<a href="javascript:void(0)" onclick="showDescr($(this).text())">'+ 
            mData.name[i]+ 
            '</a>&nbsp;<span style="font-size: x-small; font-style: italic; font-family: serif">('+mData.time[i]+')</span></div>'
        }
        $("#listing").html(listingData);
    })
}

function randFIlm() {
    $("#descrPlace").removeClass('cBlock');
    $("#descrPlace").html('');
    $("#filesPlace").html('');
    $.getJSON('bin/list.php', function(pData){
        var randNum = Math.floor(Math.random() * (pData.length - 1));
        showDescr(pData[randNum]);
    })
}
function showDescr(name) {
    window.scrollTo(0,0);
        $("#listing").html('');
        $("#descrPlace").addClass("cBlock");
        $("#descrPlace").html('');
        $("#descrPlace").append('<a target="_blank" href="http://kinobaza.tv/search?query=' + name + '&search_type=films"><div id="showName">' + name + '<div class="placeholder"></div></div></a><div class="rating" id="rating"></div>')
        $("#filesPlace").html('');
        $("#filesPlace").append('<div class="fileList">Список файлов</div>');
    $.getJSON('bin/showDescr.php', {'query':name}, function(dData){
        for(var i = 0; i < dData.files.length; i++) {
            $("#filesPlace").append('<div class="fileList">&nbsp;&ndash;&nbsp;<a href="javascript:void(0)" onclick="showFileInfo()">' + dData.files[i] + '</a></div>');
        }
        if((dData.id != 'noDescr')&&(dData.id != '')) {
            var fImage = '<img src="http://st.kinopoisk.ru/images/film/' + dData.id + '.jpg" />';
            $.getJSON('bin/rating.php', {'num':dData.id}, function(rateData){
                $("#rating").append('Кинопоиск: ' + rateData.kp[0] + ', IMDB: ' + rateData.imdb[0]);
            })
        } else {
            var fImage = '';
        }
        $("#descrPlace").append('<div class="descrText">' + fImage + '<span id="' + dData.id + '" onclick="editDescr(this)">' + dData.descr + '</span></div><div class="clear"></div>');
        $("#descrPlace").append('<span id="fullpath" style="display: none">' + dData.fullpath + '</span>')
        $(".placeholder").css('display','none');
    })
}

function resetDescr() {
    $.getJSON('bin/resetDescr.php', {'name':$('#showName').text()}, function(resData){
        if(resData != 'success') {
            alert(resData);
        } else {
            showDescr($('#showName').text());
        }
    })
}

function searchString(sString) {
    $("#descrPlace").removeClass('cBlock');
    $("#descrPlace").html('');
    var listingData = [];
    if (typeof(sString) == 'undefined') {
        var sString = $("#search").val();
    }
    $.getJSON('bin/search.php', {'str':sString,'ajax':'yes'}, function(sData){
        for(var i = 0; i < sData.length; i++) {
            listingData.push('<div class="cItem"><a href="javascript:void(0)" onclick="showDescr($(this).text())">' + sData[i] + '</a></div>');
        }
        if(listingData.length == '1') {
            var fLett = sString.substr(0,1);
            var noFLett = sString.substr(1);
            sString = fLett.toUpperCase() + noFLett;
            showDescr(sString);
//            alert(sString);
        } else {
            $("#listing").html(listingData.join(''));
        }
    })
}

var selItem = function(){
    showDescr($("#search").val());
}

function aCompl() {
    $("#search").autocomplete(
        "bin/search.php" , {
            delay:10,
            minChars:2,
            matchSubset:1,
            matchContains:1,
            cacheLength:10,
            queryParam:'str',
            extraParams: {'ajax':'no'},
            onItemSelect: selItem,
            autoFill:false
        }
    );
}

function takeString() {
    if (window.location.search != '') {
        var sString = decodeURIComponent(window.location.search);
        if (sString.length == '2') {
            // Это буква
            fListing(sString.substr(1));
        } else {
            $("#search").val(sString.substr(1));
            searchString(sString.substr(1));
        }
    } else {
    	randFIlm();
        return false;
    }
    return true;
}

function showFileInfo() {
    var overlay = '<div id="overlay">'+
        '<a style="color: white; padding: 25px 0 10px 10%;" href="javascript:void(0)" onclick="$(this).parent().remove()">Закрыть</a>'+
        '</div>';
    $(overlay).appendTo("body");
    $.get('bin/mediainfo.php', {'path':$("#fullpath").text()}, function(fiData){
        $("#overlay").append('<div id="fiData" style="padding: 10px; margin: 10px auto; background: white; width: 80%; height: 80%; max-height: 80%; max-width: 80%;  overflow: scroll; opacity: 1;">' + fiData + '</div>')
    })
}